<template>
  <div class="app-container">
    <el-row :gutter="20">

      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
          <el-form-item label="服务器地址" prop="userName">
            <el-input v-model="queryParams.domain.serverAddress" placeholder="服务器地址" clearable size="small" style="width: 240px"
              @keyup.enter.native="handleQuery" />
          </el-form-item>

          <el-form-item label="状态" prop="status">
                      <el-select
                        v-model="queryParams.domain.serverStatus"
                        placeholder="服务器状态"
                        clearable
                        size="small"
                        style="width: 240px"
                      >
                        <el-option
                          v-for="dict in serverStatusOpts"
                          :key="dict.dictValue"
                          :label="dict.dictLabel"
                          :value="dict.dictValue"
                        />
                      </el-select>
            </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
            <el-button  v-loading.lock= "jobLoading"   v-if="jobMsg.currentStep == 'stop'" type="primary" plain icon="el-icon-circle-close" size="mini" @click="dealJob">
              {{jobMsg.text}}</el-button>
            <el-button  v-loading.lock= "jobLoading" v-if="jobMsg.currentStep == 'start'" type="primary" plain icon="el-icon-circle-check" size="mini" @click="dealJob">
              {{jobMsg.text}}</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="userList" stripe border>
          <el-table-column label="服务器地址" align="center" key="serverAddress" prop="serverAddress" :show-overflow-tooltip="true" />
          <el-table-column label="状态" align="center" key="status" >
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.serverStatus"
                :active-value= '0'
                :inactive-value= '1'
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>

          <el-table-column label="运行/总数" align="center" key="runAndAll" width="80px">
            <template slot-scope="scope">
             <el-tooltip class="item" effect="dark" content="查看应用实例" placement="right-end">
                <el-button type="primary" size="mini"  @click="toJarInst(scope.row)" round>{{scope.row.runAndAll}}</el-button>
             </el-tooltip>
            </template>
          </el-table-column>

          <el-table-column label="新增日期" align="center" key="addTime" prop="addTime"  width="180px"/>
          <el-table-column label="添加方式" align="center" key="addTypeName" prop="addTypeName" :show-overflow-tooltip="true" />
          <el-table-column label="备注说明" align="center" key="asName" prop="asName" :show-overflow-tooltip="true" />
          <el-table-column label="操作" align="center" width="260" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button  size="mini"
               v-loading.lock= "loading"  type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
               <el-button  size="mini"
                v-loading.lock= "loading"  type="text" icon="el-icon-c-scale-to-original" @click="getLogs(scope.row)">查看检测日志</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
          @pagination="getList" />
      </el-col>
    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="14">
            <el-form-item label="服务器地址" prop="serverAddress">
              <el-input v-model="form.serverAddress" placeholder="服务器Ip" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18">
            <el-form-item label="添加应用" prop="appIdList">
                     <el-select  v-model="form.appIdList" multiple placeholder="请选择应用">
                     <el-option
                       v-for="item in appAllList"
                       :key="item.id"
                       :label="item.appName"
                       :value="item.id"
                     ></el-option>
                   </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="14">
            <el-form-item label="服务器注释" prop="asName">
              <el-input type="textarea" v-model="form.asName" placeholder="请输入服务器注释"  />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="14">
            <el-form-item label="注册地址" prop="registerUrl">
              <el-input v-model="form.registerUrl" placeholder="请输入客户端注册地址" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-loading.lock= "loading">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


<!-- 添加或修改参数配置对话框 -->
    <el-dialog  title="查询日志" :visible.sync="logOpen" width="800px" append-to-body>
      <el-table  v-loading="loading" :data="logList" border fit highlight-current-row style="width: 100%">
        <el-table-column label="服务器地址" align="center" key="serverAddress" prop="serverAddress"  />
        <el-table-column label="变更状态" align="center" key="changeStatusName" prop="changeStatusName" />
        <el-table-column label="检测时间" align="center" key="checkTime" prop="checkTime"  />
      </el-table>
      <pagination v-show="logTotal>0" :total="logTotal" :page.sync="logQuery.pageNum" :limit.sync="logQuery.pageSize"
        @pagination="getLogs()" />
    </el-dialog>

  </div>
</template>

<script>
  import {
    listServer,
    delServer,
    addServer,
    updateserver,
    changeStatus,
    getServerStatus,
    listLogs
  } from "@/api/server";

  import {listAllApp} from "@/api/app"

  import {getJobDetail,startJob,stopJob} from "@/api/job"

  export default {
    name: "User",
    data() {
      return {
        // 遮罩层
        loading: true,
         jobLoading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        logTotal: 0,
        // 用户表格数据
        userList: null,
        logList:[],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        logOpen:false,
        // 表单参数
        form: {},
        defaultProps: {
          children: "children",
          label: "label"
        },
        serverStatusOpts:[],

          //服务列表
        appAllList:[],
        isEdit: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          domain: {

          }
        },
        logQuery:{
          pageNum: 1,
          pageSize: 10,
          domain: {

          }
        },
        jobMsg:{},
        // 表单校验
        rules: {
          serverAddress: [{
            required: true,
            message: "服务器Ip不能为空",
            trigger: "blur"
          }],
          registerUrl: [{
            required: true,
            message: "客户端注册地址不能为空",
            trigger: "blur"
          }]
        }
      };
    },
    watch: {},
    created() {
      this.getJobMsg();
      this.getStatusOpt();
      this.getList();
      this.getAppList();
    },
    methods: {

      getLogs(row){
        this.logOpen = true;
        this.loading = true;
        this.logQuery.domain.serverId = row.id;
        listLogs(this.logQuery).then(res =>{
          this.logList = res.data.records;
          this.logTotal = res.data.total;

          this.loading = false;
        });
      },
      getJobMsg(){
        getJobDetail("checkClientJob").then(res =>{
          this.jobMsg = res.data;
        });
      },
      /***查询服务状态*/
      getStatusOpt(){
        let defaultOpt = {"dictValue":"","dictLabel":"全部"};
        this.serverStatusOpts.push(defaultOpt);
        getServerStatus().then(res =>{
          let data = res.data;
          data.map(item =>  this.serverStatusOpts.push({"dictValue":item.status,"dictLabel":item.statusName}));
        });
      },
      /**查询服务列表*/
      getAppList(){
        let query ={};
        listAllApp(query).then(res=>{
          this.appAllList = res.data;
        });
      },
      /** 查询用户列表 */
      getList() {
        this.loading = true;
        listServer(this.queryParams).then(response => {
          this.userList = response.data.records;
          this.total = response.data.total;
          this.loading = false;
        }).catch((err) => {
          this.loading = false;
        });
      },

      // 取消按钮
      cancel() {
        debugger
        this.open = false;
        this.form ={};
      },
      // 表单重置
      reset() {
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.page = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "新增服务器";
        this.form = {};
        this.isEdit = false;
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.open = true;
        this.title = "修改用户";
        this.form = JSON.parse(JSON.stringify(row ));
        this.isEdit = true;
      },
      /** 提交按钮 */
      submitForm: function() {
        this.loading = true;
        this.$refs["form"].validate(valid => {
          if (valid) {
            console.log(this.form)
            if (this.form.id != undefined) {
              updateserver(this.form).then(response => {
                 this.loading = false;
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }).catch(()=>{
                 this.loading = false;
              });
            } else {
              addServer(this.form).then(response => {
                 this.loading = false;
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }).catch(()=>{
                 this.loading = false;
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
         this.loading = true;
        const userIds = row.id;
        this.$confirm('是否确认删除?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delServer(userIds);
        }).then(() => {
          this.loading = false;
          this.msgSuccess("删除成功");
          this.getList();
        }).catch(()=>{
            this.loading = false;
        })
      },
      //变更状态
      handleStatusChange(row){
        let text = row.serverStatus === 0 ? "启用" : "停用";
        this.$confirm('确认要' + text + ':' + row.serverAddress + '吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          customClass:'del-model',
          type: 'warning'
        }).then(() => {
            return changeStatus(row.id, row.serverStatus).then(res =>{
                this.$modal.msgSuccess(text+"成功");
                 this.getList();
            });
        }).catch(() =>{
              this.getList()
        })
      },
      //跳转到详情
      toJarInst(row){
        this.$router.push({
         path: '/app/appInst',
         query: {
          serverId: row.id
         }
        })
      },
      //处理定时任务
      dealJob(){
        this.jobLoading = true;
        this.$confirm('确认要' + this.jobMsg.nextStepMsg+ '吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          customClass:'del-model',
          type: 'warning'
        }).then(() => {
            if(this.jobMsg.nextStep =='stop'){
              return stopJob("checkClientJob");
            }
            if(this.jobMsg.nextStep =='start'){
              return startJob("checkClientJob");
            }
        }).then(()=>{
          this.jobLoading = false;
          this.getJobMsg()
        }).catch(() =>{
            this.jobLoading = false;
        })
      },


    }
  };
</script>
